import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:bxultimate/app/router/router_name.dart';
import 'package:bxultimate/data/store/auth_store.dart';
import 'package:bxultimate/data/store/im_store.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';

import 'package:flutter_sound/flutter_sound.dart';

class UtilMqtt {
  FlutterSoundPlayer? _mPlayer = FlutterSoundPlayer();

  connect() async {
    if(GetPlatform.isAndroid){
      _mPlayer!.openPlayer().then((value) async {
        await _mPlayer?.startPlayerFromStream(
            codec: Codec.pcm16, numChannels: 1, sampleRate: 48000);
      });
    }

    String userId = AuthStore.to.profile.id!;

    String server = "59.110.65.142";
    int port = 1883;
    String clientId = "";
    String userName = "${userId}_android_" + randomString(8);
    String password = "${userId}_android_" + randomString(8);
    ImStore.getInstance()
        .connect(server, port, clientId, userName, password)
        .then((v) {
      if (v!.returnCode == MqttConnectReturnCode.connectionAccepted) {
        print("恭喜你~ ====mqtt连接成功");
        ImStore.getInstance().subscribeMessage("bdjw-common-topic");
        ImStore.getInstance()
            .subscribeMessage("bdjw-user-topic-1699262505246109748_uniapp");

        ImStore.getInstance()
            .updates()!
            .listen((List<MqttReceivedMessage<MqttMessage>> data) async {
          final recMess = data[0].payload as MqttPublishMessage;
          final topic = data[0].topic;

          final String pt = Utf8Decoder().convert(recMess.payload.message);
          print(
              'BDJWMQTT::Change notification:: topic is <${data[0].topic}>, payload is <-- $pt -->');
          var jsonObject = json.decode(pt);

          List<int> sound = [];

          jsonObject['data'].map((e) => sound.add(int.parse(e.toString()))).toList();
          if (topic == 'bdjw-common-topic' && jsonObject['fromId'] != AuthStore.to.profile.id) {
            Uint8List uint8list = Uint8List.fromList(sound);
            _mPlayer!.foodSink!
                .add(FoodData(uint8list));
            return;
          }


          if (jsonObject['event'] == 'invite_to_room') {
            // 启动视频或者音频
            if (jsonObject['type'] == 'video') {
              FlutterRingtonePlayer.play(
                android: AndroidSounds.ringtone,
                ios: IosSounds.glass,
                looping: true,
                // Android only - API >= 28
                volume: 0.5,
                // Android only - API >= 28
                asAlarm: false, // Android only - all APIs
              );

              var params = {
                'pageRouter': RouterName.imVideoChat,
                'roomId': jsonObject['roomId'],
                'userId': jsonObject['userId'],
                'userName': jsonObject['userName'],
                'ownUrl': jsonObject['ownUrl'],
              };

              // 将APP 唤醒

              Get.toNamed(RouterName.imVideoChat, arguments: params);
            }
          }

          // 消息操作
        });
      } else if (v.returnCode == MqttConnectReturnCode.badUsernameOrPassword) {
        print("有事做了~ ====mqtt连接失败 --密码错误!!!");
      } else {
        print("有事做了~ ====mqtt连接失败!!!");
      }
    });
  }

  // 随机数
  randomString(int length) {
    const chars =
        'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    return List.generate(
        length, (index) => chars[Random().nextInt(chars.length)]).join();
  }
}
